package com.blvtphan.tipocketclubs.gui;

import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import org.apache.http.NameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Toast;

import com.blvtphan.tipocketclubs.R;
import com.blvtphan.tipocketclubs.api.ApiConstant;
import com.blvtphan.tipocketclubs.api.ApiHelper;
import com.blvtphan.tipocketclubs.custom.CustomButton;
import com.blvtphan.tipocketclubs.custom.CustomEditText;
import com.blvtphan.tipocketclubs.custom.CustomTextView;
import com.blvtphan.tipocketclubs.system.UserSetting;
import com.blvtphan.tipocketclubs.util.ConnectionUtils;
import com.blvtphan.tipocketclubs.util.Constants;
import com.blvtphan.tipocketclubs.util.GeneralUtils;
import com.blvtphan.tipocketclubs.util.PreferenceUtils;

public class LoginActivity extends Activity {

	/* Variable */
	private Menu mMenu;
	private Context mContext;
	private CustomButton mBtnLogin;
	private CustomButton mBtnPreview;
	// private CustomCheckBox mCkbRemember;
	private CustomEditText mEdtUsername, mEdtPassword;
	private CustomTextView mTvForgotPass;

	private boolean doubleBackToExitPressedOnce = false;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

//		requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);

		setContentView(R.layout.activity_login);

		mContext = this;

//		getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE,
//				R.layout.custom_title_bar);
//		CustomTextView tvTitle = (CustomTextView) findViewById(R.id.txt_title_bar);
//		tvTitle.setText(mContext.getString(R.string.title_login_screen));

		initView();
		// Registering check Internet
		ConnectionUtils.checkConnectInternet(mContext);
		ConnectionUtils.registerCheckStateInternetConnection(mContext);
	}

	@Override
	public void onBackPressed() {
		// TODO Auto-generated method stub
		
		if (doubleBackToExitPressedOnce) {
			super.onBackPressed();
			return;
		}
		this.doubleBackToExitPressedOnce = true;
		Toast.makeText(this,
				mContext.getString(R.string.mess_back_again_to_exit),
				Toast.LENGTH_SHORT).show();
		new Handler().postDelayed(new Runnable() {

			@Override
			public void run() {
				doubleBackToExitPressedOnce = false;
			}
		}, 2000);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_main, menu);
		mMenu = menu;
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// TODO Auto-generated method stub
		switch (item.getItemId()) {
		case R.id.action_language_en:
			changeLocalLanguage(Locale.ENGLISH);
			return true;
		case R.id.action_language_vi:
			changeLocalLanguage(new Locale("VIETNAMESE"));
			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}

	/**
	 * 
	 */
	private void initView() {

		// mCkbRemember = (CustomCheckBox) findViewById(R.id.ckb_remember);
		// mCkbRemember.setOnClickListener(new OnClickListener() {
		// @Override
		// public void onClick(View v) {
		//
		// }
		// });

		mEdtUsername = (CustomEditText) findViewById(R.id.txt_username);
		mEdtPassword = (CustomEditText) findViewById(R.id.txt_password);
		mTvForgotPass = (CustomTextView) findViewById(R.id.txt_forgot_password);

		// View
		mBtnLogin = (CustomButton) findViewById(R.id.btn_login);
		mBtnLogin.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {

				String email = mEdtUsername.getText().toString();
				String password = mEdtPassword.getText().toString();
				// String ipServer = mEdtIpServer.getText().toString().trim();

				// Add Ip server
				// UserSetting.getInstance().setIpServer(ipServer);

				// Check input username and password
				if (password.length() == 0 || email.length() == 0) {
					Toast.makeText(
							mContext,
							mContext.getString(R.string.msg_please_input_username_password),
							Toast.LENGTH_SHORT).show();
					return;
				}

				doTipocketLogin(email, password);
				
			}
		});

		mBtnPreview = (CustomButton) findViewById(R.id.btn_preview);
		mBtnPreview.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				doTipocketLogin("guest@tipocket.com", "tipocket");
			}
		});
		
		mTvForgotPass.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				String url = ApiConstant.FORGOT_PASS_URL;
				Intent i = new Intent(Intent.ACTION_VIEW);
				i.setData(Uri.parse(url));
				startActivity(i);
			}
		});

	}
	
	private void doTipocketLogin(String email, String password) {
		// Check Internet
		if (UserSetting.getInstance().isConnectInternet) {

			String url = ApiHelper.genAPI(ApiConstant.API.API_LOGIN);// +
																		// "?email=guest@tipocket.com&password=tipocket";

			Map<String, String> params = new HashMap<String, String>();
			params.put("email", email);
			params.put("password", password);

			List<NameValuePair> contents = PreferenceUtils
					.createHttpParams(params);
			// content =
			// ApiHelper.getJSONObjectLogin("guest@tipocket.com",
			// "tipocket").toString();
			ConnectionUtils.ExcuteHttpPostThread excuteHttpPost = new ConnectionUtils.ExcuteHttpPostThread(
					mContext, mProcessLogin, url, contents);
			excuteHttpPost.execute();

		} else {
			// No Internet Access
			GeneralUtils.showAlertDialog(mContext,
					mContext.getString(R.string.error_title),
					mContext.getString(R.string.msg_no_internet_access));
		}
	}

	/**
	 * Handler login
	 */
	private Handler mProcessLogin = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case Constants.APIConstant.HANDLER_REQUEST_FAIL:
				// Connect fail
				GeneralUtils.showAlertDialog(mContext,
						mContext.getString(R.string.error_title),
						mContext.getString(R.string.msg_acc_not_correct));
				break;
			case Constants.APIConstant.HANDLER_REQUEST_SUCCESS:
				String result = (String) msg.obj;
				Log.i("LoginActivity", result);
				try {
					JSONObject obj = new JSONObject(result);
					if (!obj.getString(ApiConstant.JsonType.DATA).equals("")) {
						// Set userId
						JSONObject dataObj = obj.getJSONObject(ApiConstant.JsonType.DATA);
						UserSetting.getInstance().setUserId(dataObj.getString(ApiConstant.User.ID));
						UserSetting.getInstance().setToken(dataObj.getString(ApiConstant.User.TOKEN));
						UserSetting.getInstance().setUserFullName(dataObj.getString(ApiConstant.User.FIRST_NAME)+" "+dataObj.getString(ApiConstant.User.LAST_NAME));
						if(!dataObj.isNull(ApiConstant.User.EMAIL))
							UserSetting.getInstance().setEmail(dataObj.getString(ApiConstant.User.EMAIL));	
						if(!dataObj.isNull(ApiConstant.User.COMPANY) && !dataObj.getString(ApiConstant.User.COMPANY).equals(""))
							UserSetting.getInstance().setCompany(dataObj.getString(ApiConstant.User.COMPANY));
						else 
							UserSetting.getInstance().setCompany("TiPocket");
						// Go to main page
						Intent intent = new Intent(mContext, MainActivity.class);
						startActivity(intent);
					} else {
						
					}
				} catch (JSONException e) {
					e.printStackTrace();
					// Wrong
					GeneralUtils.showAlertDialog(mContext,
							mContext.getString(R.string.error_title),
							mContext.getString(R.string.msg_connect_servier_fail));
				}
				break;
			default:
				break;
			}
		}
	};

	/**
	 * Change Local Language
	 */
	private void changeLocalLanguage(Locale locale) {
		Configuration newConfig = new Configuration();
		newConfig.locale = locale;
		onConfigurationChanged(newConfig);
	}

	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);

		// Set default Language
		Locale.setDefault(newConfig.locale);
		getBaseContext().getResources().updateConfiguration(newConfig,
				getResources().getDisplayMetrics());

		// Refresh UI
		setTitle(R.string.app_name);
		setContentView(R.layout.activity_login);
		initView();
		if (mMenu != null) {
			mMenu.clear();
			getMenuInflater().inflate(R.menu.activity_main, mMenu);
		}

		// Inform
		Toast.makeText(
				mContext,
				getResources().getString(R.string.change_language_successfully),
				Toast.LENGTH_SHORT).show();
	}

	@Override
	protected void onDestroy() {
		ConnectionUtils.unregisterCheckStateInternetConnection(mContext);
		super.onDestroy();
	}
}
